const cloud = require('wx-server-sdk');

// 初始化云开发
cloud.init({
  env: 'liucheng-2gmqvcgs50e86304' // 使用指定的云环境
});

// 初始化数据库
const db = cloud.database();

exports.main = async (event, context) => {
  const {
    user, //用户
    manufactor, //厂家
    orderNumber, //订单号
    taobaoNumber, //淘宝订单号
    advancePayment, //预付款
    orderTime, //下单时间
    expectDeliTime, //预际交货时间
    realityTime, //实际交货时间
    customerAddress, //地址
    orderCompleted, //是否完成
    afterSale, //售后
    remarks, //评论
    billingType, //开票类型
  } = event;

  try {
    const currentTime = new Date();

    const result = await db.collection('Order').add({
      data: {
        user: user, //用户
        manufactor: manufactor, //厂家
        orderNumber: orderNumber, //订单号
        taobaoNumber: taobaoNumber, //淘宝订单号
        advancePayment: advancePayment, //预付款 
        orderTime: orderTime, //下单时间
        expectDeliTime: expectDeliTime, //预际交货时间
        realityTime: realityTime, //实际交货时间
        customerAddress: customerAddress, //地址
        orderCompleted: orderCompleted, //是否完成
        afterSale: afterSale, //售后
        remarks: remarks, //评论
        billingType: billingType, //开票类型
        createdAt: currentTime,
        updatedAt: currentTime,
      }
    });

    return {
      success: true,
      orderId: result._id
    };
  } catch (err) {
    console.error('Error creating order:', err);
    return {
      success: false,
      errorMessage: err
    };
  }
};